// vm.cpp
//
// Copyright (C) 2008  Maksim Sipos <msipos@mailc.net>
//
// This file is a part of the Ripe language project.
//
// Ripe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "util/standard.hpp"
#include "util/serialize.hpp"
#include "types/object.hpp"
#include "vm/vm.hpp"

namespace Ripe {

VM::VM()
{
}

void VM::load(std::istream* input_stream)
{
  ISerializer ser(input_stream);
  ErrorVMFileLoad e;
  
  try {
    char* magic = ser.unserialize_string();
    if (strcmp(magic, "RipeVM") != 0){
      e.message = "Invalid magic string.";
      throw e;
    }

    // Check the version
    uint32_t ver = ser.unserialize_uint32();
    if (ver > R_VER_MAJOR){
      e.message = "This program needs newer version of Ripe.";
      throw e;
    }
    ver = ser.unserialize_uint32(); // TODO: Think of something to do with
                                    // minor version.

    uint32_t n_sections = ser.unserialize_uint32();
    for (uint32_t i = 0; i < n_sections; i++){
      uint32_t sct_flags = ser.unserialize_uint32();
      char* sct_name = ser.unserialize_string();
      
      // Analyze sct_flags and sct_name to find the way to parse this section
      if (sct_flags & R_SECTION_CODE) {
      
      }
    }
  } catch (const ErrorUnserialize& err) {
    e.message = "VM file corrupted.";
    throw e;
  }
}

}
